﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolLibrary.Entity;
using SchoolLibrary.Entity.Person;

namespace SchoolLibrary.DataBase.DAO
{
    public class BookDAO : AbstractDAO<Book>
    {
        private static BookDAO instance;

        private BookDAO() { }

        public static BookDAO getInstance()
        {
            if (instance == null)
            {
                instance = new BookDAO();
            }
            return instance;
        }

        public override List<Book> findAll() 
        {
            Query query = new Query(Book.FIND_BOOKS);
            return getDAOHelper().getResultList(query);
        }

        public override Book findById(long id)
        {
            Query query = new Query(Book.FIND_BY_ID);
            query.setParameter("id", id);
            return getDAOHelper().getSingleResult(query);
        }

        public override void save(Book book)
        {
            if (book.Id != UNDIFINED_ID)
            {
                Query deleteWriterQuery = new Query(Book.DELETE_WRITERS_BY_BOOK_ID);
                deleteWriterQuery.setParameter("id", book.Id);
                getDAOHelper().executeUpdate(deleteWriterQuery);
                save(book, Book.UPDATE);
            }
            else
            {
                save(book, Book.SAVE);
            }

        }


        private void save(Book book, string queryString)
        {
            Query query = new Query(queryString);
            query.setParameter("id", book.Id);
            query.setParameter("name", book.Name);
            query.setParameter("year", book.Year);
            query.setParameter("price", book.Price);
            query.setParameter("amount", book.Amount);
            query.setParameter("genreId", book.Genre.Id);
            getDAOHelper().executeUpdate(query);


            foreach (Writer writer in book.Writers)
            {
                Query addWriterQuery = new Query(Book.ADD_WRITER_TO_BOOK);
                long id = book.Id == Identity.UNDEFINED_ID ? getDAOHelper().getLastId(Book.TABLE_NAME) : book.Id;
                addWriterQuery.setParameter("bookId", id);
                addWriterQuery.setParameter("writerId", writer.Id);
                getDAOHelper().executeUpdate(addWriterQuery);
            } 
        }

        public List<Book> findByName(string name)
        {
            Query query = new Query(Book.FIND_BOOK_NAME);
            query.setStringParameter("name", name);
            return getDAOHelper().getResultList(query);
        }
      
    }
}
